import { platformApi } from '../../api';
import type { PlatformUser } from '../../../types/platform';
import type { PageResponse } from '../../api';

// 平台用户查询参数（匹配后端API）
interface PlatformUserQueryParams {
  page?: number;
  size?: number;
  current?: number;
  search?: string;
  username?: string;
  realName?: string;
  email?: string;
  status?: number; // 后端使用数字：1-正常，2-锁定，0-禁用
}

// 扩展PlatformUser类型以包含password字段（用于创建用户）
interface PlatformUserWithPassword extends PlatformUser {
  password?: string;
}

// 由于响应拦截器已经处理了数据提取，创建一个类型安全的请求方法
const request = <T>(config: any): Promise<T> => {
  return platformApi.request(config) as Promise<T>;
};

/**
 * 真实后端API实现
 */
const realPlatformUsersApi = {
  /**
   * 获取平台用户列表（分页）
   */
  getUsers: async (params?: PlatformUserQueryParams): Promise<PageResponse<PlatformUser>> => {
    const query = {
      current: params?.page || 1,
      size: params?.size || 10,
      username: params?.search,
      realName: params?.search,
      email: params?.search,
      status: params?.status,
      ...params
    };
    
    return request<PageResponse<PlatformUser>>({
      url: '/api/v3/platform/users/page',
      method: 'POST',
      data: query,
    });
  },

  /**
   * 获取平台用户详情
   */
  getUser: async (userId: string | number): Promise<PlatformUser> => {
    return request<PlatformUser>({
      url: `/api/v3/platform/users/get/${userId}`,
      method: 'GET',
    });
  },

  /**
   * 创建平台用户
   */
  createUser: async (userData: Partial<PlatformUserWithPassword>): Promise<void> => {
    // 转换前端数据格式到后端格式
    const dto = {
      username: userData.username,
      password: userData.password || '123456', // 默认密码
      realName: userData.realName,
      email: userData.email,
      phone: userData.phone,
      avatar: userData.avatar,
      status: userData.status === 'active' ? 1 : userData.status === 'locked' ? 2 : 0,
      roleIds: userData.platformRoles, // 直接传递角色ID数组
    };
    
    await request<void>({
      url: '/api/v3/platform/users/add',
      method: 'POST',
      data: dto,
    });
  },

  /**
   * 更新平台用户
   */
  updateUser: async (userId: string | number, userData: Partial<PlatformUser>): Promise<void> => {
    // 转换前端数据格式到后端格式
    const dto = {
      id: userId, // 保持原始格式，避免精度丢失
      username: userData.username,
      realName: userData.realName,
      email: userData.email,
      phone: userData.phone,
      avatar: userData.avatar,
      status: userData.status === 'active' ? 1 : userData.status === 'locked' ? 2 : 0,
      roleIds: userData.platformRoles, // 直接传递角色ID数组
    };
    
    await request<void>({
      url: '/api/v3/platform/users/update',
      method: 'PUT',
      data: dto,
    });
  },

  /**
   * 删除平台用户
   */
  deleteUser: async (userId: string | number): Promise<void> => {
    await request<void>({
      url: `/api/v3/platform/users/delete/${userId}`,
      method: 'DELETE',
    });
  },

  /**
   * 锁定/解锁用户
   */
  toggleUserStatus: async (userId: string | number, status: 'active' | 'locked'): Promise<void> => {
    const statusCode = status === 'active' ? 1 : 2;
    await request<void>({
      url: `/api/v3/platform/users/${userId}/toggle-status`,
      method: 'POST',
      data: { status: statusCode },
    });
  },

  /**
   * 重置用户密码
   */
  resetPassword: async (userId: string | number): Promise<{ newPassword: string }> => {
    return request<{ newPassword: string }>({
      url: `/api/v3/platform/users/${userId}/reset-password`,
      method: 'POST',
    });
  },

  /**
   * 获取用户角色
   */
  getUserRoles: async (userId: string | number): Promise<string[]> => {
    return request<string[]>({
      url: `/api/v3/platform/users/${userId}/roles`,
      method: 'GET',
    });
  },

  /**
   * 分配用户角色
   */
  assignUserRoles: async (userId: string | number, roleIds: string[]): Promise<void> => {
    await request<void>({
      url: `/api/v3/platform/users/${userId}/assign-roles`,
      method: 'POST',
      data: roleIds,
    });
  },

  /**
   * 检查用户名是否存在
   */
  checkUsernameExists: async (username: string, excludeId?: string | number): Promise<{ exists: boolean }> => {
    return request<{ exists: boolean }>({
      url: '/api/v3/platform/users/check-username',
      method: 'GET',
      params: { username, excludeId },
    });
  },

  /**
   * 检查邮箱是否存在
   */
  checkEmailExists: async (email: string, excludeId?: string | number): Promise<{ exists: boolean }> => {
    return request<{ exists: boolean }>({
      url: '/api/v3/platform/users/check-email',
      method: 'GET',
      params: { email, excludeId },
    });
  },
};



/**
 * 平台用户管理API服务
 * 直接使用真实API实现
 */
export const platformUsersApi = realPlatformUsersApi;

export default platformUsersApi;